package com.hc.controller;

import com.hc.common.bean.PageBean;
import com.hc.common.bean.Result;
import com.hc.common.bean.ResultUtil;
import com.hc.common.enums.ResultEnum;
import com.hc.common.oss.AliOSSUtil;
import com.hc.common.utils.encode.Base64Util;
import com.hc.domain.User;
import com.hc.ex.GlobalException;
import com.hc.query.UserCondition;
import com.hc.res.UserItem;
import com.hc.service.UserService;
import com.hc.vo.PassVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.Null;
import java.io.IOException;
import java.io.Serializable;
import java.util.Objects;

/**
 * 用户 controller
 * @author 六月Bing
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 添加用户
     * @param user
     * @param img
     * @return
     */
    @PostMapping("/v1")
    public Result<Null> create(@RequestBody User user,
                               @RequestPart("img") MultipartFile img
    ) {
        if (userService.checkNickname(user.getNickname())){
            return ResultUtil.fail("用户名已经存在");
        }
        if (!ObjectUtils.isEmpty(user.getPassword())){
            user.setPassword(Base64Util.encode(user.getPassword()));
        }
        if (!ObjectUtils.isEmpty(img)){
            String avatarUrl = null;
            try {
                avatarUrl = AliOSSUtil.upload(img);
            } catch (IOException e) {
                throw new GlobalException(408, "图片上传到图片服务器出错");
            }
            user.setAvatar(avatarUrl);
        }
        boolean res = userService.save(user);
        return res ? ResultUtil.success("添加成功") : ResultUtil.fail("添加失败");
    }

    /**
     * 修改用户
     * @param user 前端页面传入的修改的用户信息
     */
    @PutMapping("/v1")
    public Result<Null> updateById(@RequestBody User user) {
        boolean res = userService.updateById(user);
        return res ? ResultUtil.success("更新成功") : ResultUtil.fail("更新失败");
    }

    /**
     * 删除用户
     * @param id 用户主键
     */
    @DeleteMapping("/v1/{id}")
    public Result<Null> removeById(@PathVariable Serializable id) {
        boolean res = userService.removeById(id);
        return res ? ResultUtil.success("删除成功") : ResultUtil.fail("删除失败");
    }

    /**
     * 通过用户id查询指点用户信息
     * @param id 用户id
     */
    @GetMapping("{id}")
    public Result<User> getById(@PathVariable Serializable id) {
        User res = userService.getById(id);
        return ResultUtil.<User>success("查询成功").setData(res);
    }
    /**
     * 查询当前登录用户的信息
     */
    @GetMapping("/selectSession/{id}")
    public Result<User> getBySessionId(HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        User res = userService.getById(user.getId());
        return ResultUtil.<User>success("查询成功").setData(res);
    }

    /**
     * 条件查询用户列表
     */
    @GetMapping("/v1/getByCondition")
    public Result<PageBean<UserItem>> getByCondition(UserCondition condition) {
        if (condition == null) {
            throw new GlobalException(ResultEnum.PARAM_ERROR);
        }
        // 条件查询用户列表，返回pageBean对象
        PageBean<UserItem> userItemPageBean = userService.queryByCondition(condition);
        return ResultUtil.<PageBean<UserItem>>success("查询成功").setData(userItemPageBean);
    }

      /**
     * 修改密码
     */
    @DeleteMapping("/{id}")
    public Result<Null> updatePwd(PassVO passVO, HttpSession session) {
        // 先判断两次输入的新密码是否一致
        if (Objects.equals(passVO.getNewPass(), passVO.getConfirmPass())){
            User user = (User) session.getAttribute("loginUser");
            // 判断原密码是否和登录用户的数据库密码是否一致
            if (Base64Util.encode(passVO.getOldPass()).equals(user.getPassword())){
                String encode = Base64Util.encode(passVO.getNewPass());
                user.setPassword(encode);
                boolean res = userService.updateById(user);
                session.setAttribute("loginUser",user);
                return res ? ResultUtil.success("修改成功") : ResultUtil.fail("修改成功");
            }else {
                return ResultUtil.fail("原密码输入错误");
            }
        }else {
            return ResultUtil.fail("两次密码不一致");
        }
    }
}